﻿using AK.Wwise;
using AudioStudio.Components;
using DavidJalbert.TinyCarControllerAdvance;
using EVP;
using FluffyUnderware.DevTools.Extensions;
using ImageEffects;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
using Yoozoo.Gameplay.Liberty.AI;
using Yoozoo.Gameplay.Liberty.Media;
using Yoozoo.Mars.Got;

namespace Yoozoo.Gameplay.Liberty.VehicleController
{
    [CustomEditor(typeof(ConvertCarTools))]
    public class ConvertCarToolsEditor: UnityEditor.Editor
    {
        ConvertCarTools convertCarTools;
        public override void OnInspectorGUI()
        {
           
            if (GUILayout.Button("（设置车辆根节点(如RPG_Car_Audi_0)）尝试匹配"))
            {
                if (target != null)
                {
                    convertCarTools = target as ConvertCarTools;
                    var transform = convertCarTools.transform;
                    //如果不设置，就默认为当前节点
                    if (convertCarTools.Car_Name_Root == null)
                    {
                        var CarRoot = transform;
                        convertCarTools.Car_Name_Root = CarRoot;
                    }
                    
                  
                    var carName = convertCarTools.Car_Name_Root.name;
                    
                    
                    var wheels = convertCarTools.GetComponentsInChildren<TCCAWheel>();
                    foreach (var wheel in wheels)
                    {
                        wheel.transform.gameObject.name = "Wheel1";
                    }
                    
                    
                    var lod0 = FindChildByName(transform,carName + "_LOD0");
                    if (lod0 == null)
                    {
                        carName = carName.Replace("RPG_", "");
                        lod0  = FindChildByName(transform,carName + "_LOD0");
                    }
                    var lod1 = FindChildByName(transform,carName+"_LOD1");
                    var lod2 = FindChildByName(transform,carName+"_LOD2");
                    
                    var carRoot = convertCarTools.Car_Name_Root;
                    
                    var carBody = FindChildByName(transform,carName.Replace("RPG_Car_",""));
                    carBody = carBody!=null?carBody:FindChildByName(transform,carName+"_cheshen");
                    carBody = carBody!=null?carBody:FindChildByName(transform,carName+"_BASE");
                    var doorRL = FindChildByName(transform,carName + "_DOOR_04");
                    if (doorRL == null)
                    {
                        doorRL = FindChildByName(transform,carName + "_DOOR_LB");
                    }
                    var doorFL = FindChildByName(transform,carName + "_DOOR_02");
                    
                    if (doorFL == null)
                    {
                        doorFL = FindChildByName(transform, carName + "_DOOR_LF");
                    }
                    var doorRR = FindChildByName(transform,carName + "_DOOR_03");
                    doorRR = doorRR!=null ? doorRR : FindChildByName(transform,carName + "_DOOR_RB");

                    var doorFR = FindChildByName(transform,carName + "_DOOR_01");
                    doorFR = doorFR!=null?doorFR:FindChildByName(transform,carName + "_DOOR_RF");

                    var frontPoint = FindChildByName(transform,"frontPoint");
                    var backPoint = FindChildByName(transform,"backPoint");
                    var leftDoorPoint = FindChildByName(transform,"leftDoorPoint");
                    var rightDoorPoint = FindChildByName(transform,"rightDoorPoint");
                    var leftSeatPoint = FindChildByName(transform,"leftSeatPoint");
                    var rightSeatPoint = FindChildByName(transform,"rightSeatPoint");
                    var AudioEmitter = FindChildByName(transform,"AudioEmitter");
                    
                    var tireFR = FindChildByName(transform,carName + "_W_RF001");
                    tireFR = tireFR!=null?tireFR:FindChildByName(transform,carName + "_W_RF002");
                    tireFR = tireFR!=null?tireFR:FindChildByName(transform,carName + "_W_RF");
                    tireFR = tireFR!=null?tireFR:FindChildByName(transform,carName + "_W_RF01");
                    
                    var tireFL = FindChildByName(transform,carName + "_W_LF001");
                    tireFL = tireFL!=null?tireFL:FindChildByName(transform,carName + "_W_LF002");
                    tireFL = tireFL!=null?tireFL:FindChildByName(transform,carName + "_W_LF");
                    tireFL = tireFL!=null?tireFL:FindChildByName(transform,carName + "_W_LF01");
                    
                    var tireRR = FindChildByName(transform,carName + "_W_RB001");
                    tireRR = tireRR!=null?tireRR:FindChildByName(transform,carName + "_W_RB002");
                    tireRR = tireRR!=null?tireRR:FindChildByName(transform,carName + "_W_RB");
                    tireRR = tireRR!=null?tireRR:FindChildByName(transform,carName + "_W_RB01");
                    
                    var tireRL = FindChildByName(transform,carName + "_W_LB001");
                    tireRL = tireRL!=null?tireRL:FindChildByName(transform,carName + "_W_LB002");
                    tireRL = tireRL!=null?tireRL:FindChildByName(transform,carName + "_W_LB");
                    tireRL = tireRL!=null?tireRL:FindChildByName(transform,carName + "_W_LB01");

                    convertCarTools.LOD0 = lod0;  
                    convertCarTools.LOD1 = lod1;
                    convertCarTools.LOD2 = lod2;
                    convertCarTools.Car_Root = carRoot;
                    convertCarTools.Car_Body = carBody;
                    convertCarTools.Door_FR = doorFR;
                    convertCarTools.Door_FL = doorFL;
                    convertCarTools.Door_RR = doorRR;
                    convertCarTools.Door_RL = doorRL;
                    convertCarTools.frontPoint = frontPoint;
                    convertCarTools.backPoint = backPoint;
                    convertCarTools.leftDoorPoint = leftDoorPoint;
                    convertCarTools.rightdoorPoint = rightDoorPoint;
                    convertCarTools.leftSeatPoint = leftSeatPoint;
                    convertCarTools.rightSeatPoint = rightSeatPoint;   
                    convertCarTools.Tire_FR = tireFR;
                    convertCarTools.Tire_FL = tireFL;
                    convertCarTools.Tire_RR = tireRR;
                    convertCarTools.Tire_RL = tireRL;
                    convertCarTools.audioEmitter = AudioEmitter;
                    
                   

                }
            }
            
            
            
            base.OnInspectorGUI();
            
            if (GUILayout.Button("转换"))
            {
                if (target != null)
                {
                    convertCarTools = target as ConvertCarTools;
                    reorganizeNode(convertCarTools);  
                    AddComponents(convertCarTools);
                }
                
            }
        }

        private void AddComponents(ConvertCarTools convertCarTools)
        {
            var carEntiry = convertCarTools.Car_Root.parent.GetComponent<CarEntity>();
            var audioComponent = convertCarTools.Car_Root.parent.GetComponentInChildren<VehicleAudioComponent>();
            carEntiry.audioComponent = audioComponent;

            var vehicleSetting = carEntiry.transform.GetComponent<VehicleSetting>();
            vehicleSetting.playerMaxSpeed = 70;

            var lightElement = carEntiry.transform.GetComponent<LightElement>();
            lightElement.enabled = false;
            
            var vehicleInteriorComponent = carEntiry.transform.GetComponent<VehicleInteriorComponent>();
            vehicleInteriorComponent.enabled = false;
            
            


            var tccaBody = convertCarTools.LOD0.GetComponent<TCCABody>();
            GameObject.DestroyImmediate(tccaBody);

            var rigidbody = convertCarTools.LOD0.GetOrAddCompoment<Rigidbody>();
            rigidbody.mass = 1000;
            rigidbody.angularDrag = 0;
            rigidbody.drag = 0;
            rigidbody.interpolation = RigidbodyInterpolation.Interpolate;
            rigidbody.collisionDetectionMode = CollisionDetectionMode.Discrete;
            
            var boxCollider = convertCarTools.LOD0.GetOrAddCompoment<BoxCollider>();
            var template = AssetDatabase.LoadAssetAtPath<GameObject>(
                "Assets/ResourcesAssets/Hanging/Prefabs/Car/CustomCar/Car_Template.prefab");
            var templateObj = GameObject.Instantiate(template);
            var vehicleControllerTemlateObj = templateObj.transform.GetComponentInChildren<EVP.VehicleController>();
            UnityEditorInternal.ComponentUtility.CopyComponent(vehicleControllerTemlateObj);
            var vehicleController = convertCarTools.LOD0.AddComponent<EVP.VehicleController>();
            UnityEditorInternal.ComponentUtility.PasteComponentValues(vehicleController);
            var wheelData = new Wheel();
            vehicleController.wheels[0] = wheelData;
            wheelData.wheelCollider = convertCarTools.WheelFL;
            wheelData.wheelTransform = convertCarTools.Tire_FL;
            wheelData.steer = true;
            wheelData.drive = false;
            wheelData.brake = true;
            wheelData.handbrake = false;
            
            var wheelData1 = new Wheel();
            vehicleController.wheels[1] = wheelData1;
            wheelData1.wheelCollider = convertCarTools.WheelFR;
            wheelData1.wheelTransform = convertCarTools.Tire_FR;
            wheelData1.steer = true;
            wheelData1.drive = false;
            wheelData1.brake = true;
            wheelData1.handbrake = false;

            var wheelData2 = new Wheel();
            vehicleController.wheels[2] = wheelData2;
            wheelData2.wheelCollider = convertCarTools.WheelRL;
            wheelData2.wheelTransform = convertCarTools.Tire_RL;
            wheelData2.steer = false;
            wheelData2.drive = true;
            wheelData2.brake = true;
            wheelData2.handbrake = true;
            
            var wheelData3 = new Wheel();
            vehicleController.wheels[3] = wheelData3;
            wheelData3.wheelCollider = convertCarTools.WheelRR;
            wheelData3.wheelTransform = convertCarTools.Tire_RR;
            wheelData3.steer = false;
            wheelData3.drive = true;
            wheelData3.brake = true;
            wheelData3.handbrake = true;
            
             var vehicleStandardInput = convertCarTools.LOD0.GetOrAddCompoment<VehicleStandardInput>();

             var vte = templateObj.GetComponentInChildren<VehicleTireEffects>();
             ComponentUtility.CopyComponent(vte);
             var vehicletireeffects = convertCarTools.LOD0.GetOrAddCompoment<VehicleTireEffects>();
             ComponentUtility.PasteComponentValues(vehicletireeffects);
             
             var rigidbodypuse = convertCarTools.LOD0.GetOrAddCompoment<RigidbodyPause>();
             var vehiclevisualeffects = convertCarTools.LOD0.GetOrAddCompoment<VehicleVisualEffects>();
             vehiclevisualeffects.brakesRenderer = this.convertCarTools.Car_Body.GetComponent<MeshRenderer>();
             
             var  templateToneSound = templateObj.GetComponentInChildren<LoopAdjustToneSound>();
             UnityEditorInternal.ComponentUtility.CopyComponent(templateToneSound);
             
             
             var loopAdjustToneSound = convertCarTools.LOD0.GetOrAddCompoment<LoopAdjustToneSound>();
             UnityEditorInternal.ComponentUtility.PasteComponentValues(loopAdjustToneSound);
             
            
             
             
             //loopAdjustToneSound.rtpc;
             var vehicleCollisionSound = convertCarTools.LOD0.GetOrAddCompoment<VehicleCollisionSound>();
             vehicleCollisionSound.audioComponent = audioComponent;
             var vehicleAudioByWwise = convertCarTools.LOD0.GetOrAddCompoment<VehicleAudioByWwise>();
             vehicleAudioByWwise.audioComponent = audioComponent;
             
           
             
             var wheels = convertCarTools.LOD0.GetComponentsInChildren<TCCAWheel>();
             foreach (var wheel in wheels)
             {
                 GameObject.DestroyImmediate(wheel.transform.gameObject);
             }
             
               
             TCCAPlayer tccaPlayer = convertCarTools.Car_Root.GetComponent<TCCAPlayer>();
             tccaPlayer.isTCCA = false;
             UnityEditorInternal.ComponentUtility.CopyComponent(tccaPlayer);
             UnityEditorInternal.ComponentUtility.PasteComponentAsNew(convertCarTools.Car_Root.parent.gameObject);
             GameObject.DestroyImmediate(tccaPlayer.gameObject);
        }

        private Transform FindChildByName(Transform transform, string name)
        {
            var childCount = transform.childCount;
            if (childCount > 0)
            {
                for (int i = 0; i < childCount; i++)
                {
                    var child = transform.GetChild(i);
                    if (child.name == name)
                    {
                        return child;
                    }else if (child.childCount > 0)
                    {
                        var findResult = FindChildByName(child, name);
                        if (findResult!=null)
                        {
                            return findResult;
                        }
                    }
                }
            }

            return null;
        }
        private static void reorganizeNode(ConvertCarTools convertCarTools)
        {
            if (convertCarTools.Car_Root)
            {
                convertCarTools.Car_Root.name = "Car_RootX";
            }
            else
            {
                return;
            }
           
            if (convertCarTools.LOD0)
            {
                convertCarTools.LOD0.name = "Car_Root";
                convertCarTools.LOD0.parent = convertCarTools.Car_Root.parent;
            }
            else
            {
                return;
            }

            if (convertCarTools.LOD1)
            {
                convertCarTools.LOD1.name = "Car_LOD1";
                convertCarTools.LOD1.parent = convertCarTools.LOD0;
            }
            if (convertCarTools.LOD2)
            {
                convertCarTools.LOD2.name = "Car_LOD2";
                convertCarTools.LOD2.parent = convertCarTools.LOD0;
            }
            
            GameObject carbase = new GameObject("Car_LOD0");
            carbase.transform.parent = convertCarTools.LOD0;
            GameObject Pivot = new GameObject("Pivot");
            Pivot.transform.parent = convertCarTools.LOD0;
      
            convertCarTools.Car_Body.name = "Body";
            convertCarTools.Car_Body.transform.parent = carbase.transform;
            if (convertCarTools.Door_FR)
            {
                convertCarTools.Door_FR.name = "Door_FR";
                convertCarTools.Door_FR.transform.parent = carbase.transform;
                convertCarTools.Door_FL.name = "Door_FL";
                convertCarTools.Door_FL.transform.parent = carbase.transform;
            }
       
            if (convertCarTools.Door_RR)
            {
                convertCarTools.Door_RR.name = "Door_RR";
                convertCarTools.Door_RR.transform.parent = carbase.transform;
                convertCarTools.Door_RL.name = "Door_RL";
                convertCarTools.Door_RL.transform.parent = carbase.transform;
            }
            //把显示的轮胎放到carbase下
            convertCarTools.Tire_FR.name = "Tire_FR";
            convertCarTools.Tire_FR.transform.parent = carbase.transform;
            convertCarTools.Tire_FL.name = "Tire_FL";
            convertCarTools.Tire_FL.transform.parent = carbase.transform;
            convertCarTools.Tire_RR.name = "Tire_RR";
            convertCarTools.Tire_RR.transform.parent = carbase.transform;
            convertCarTools.Tire_RL.name = "Tire_RL";
            convertCarTools.Tire_RL.transform.parent = carbase.transform;
            
            convertCarTools.frontPoint.parent = Pivot.transform;
            convertCarTools.backPoint.parent = Pivot.transform;
            convertCarTools.leftDoorPoint.parent = Pivot.transform;
            convertCarTools.rightdoorPoint.parent = Pivot.transform;
            convertCarTools.leftSeatPoint.parent = Pivot.transform;
            if (convertCarTools.rightSeatPoint)
            {
                convertCarTools.rightSeatPoint.parent = Pivot.transform;
            }
            convertCarTools.audioEmitter.parent = Pivot.transform;
            
            var wheelTemplate = AssetDatabase.LoadAssetAtPath<GameObject>(
                "Assets/ResourcesAssets/Hanging/Prefabs/Car/CustomCar/WheelColliders.prefab");
            var WheelColliders = GameObject.Instantiate(wheelTemplate, convertCarTools.LOD0);
            WheelColliders.name = "WheelColliders";
            convertCarTools.WheelFL = WheelColliders.transform.Find("WheelFL").GetComponent<WheelCollider>();
            convertCarTools.WheelFL.transform.position = convertCarTools.Tire_FL.transform.position;
            var wheelFlCenter = convertCarTools.WheelFL.center;
            convertCarTools.WheelFL.center = Vector3.zero;
            
            convertCarTools.WheelFR = WheelColliders.transform.Find("WheelFR").GetComponent<WheelCollider>();
            convertCarTools.WheelFR.transform.position = convertCarTools.Tire_FR.transform.position;
            var wheelFrCenter = convertCarTools.WheelFR.center;
            convertCarTools.WheelFR.center = Vector3.zero;
            
            convertCarTools.WheelRL = WheelColliders.transform.Find("WheelRL").GetComponent<WheelCollider>();
            convertCarTools.WheelRL.transform.position = convertCarTools.Tire_RL.transform.position;
            var wheelRlCenter = convertCarTools.WheelRL.center;
            convertCarTools.WheelRL.center = Vector3.zero;
            
            convertCarTools.WheelRR = WheelColliders.transform.Find("WheelRR").GetComponent<WheelCollider>();
            convertCarTools.WheelRR.transform.position = convertCarTools.Tire_RR.transform.position;
            var wheelRrCenter = convertCarTools.WheelRR.center;
            convertCarTools.WheelRR.center = Vector3.zero;
            
            
            
            var wheels = convertCarTools.GetComponentsInChildren<TCCAWheel>();
            foreach (var wheel in wheels)
            {
                GameObject.DestroyImmediate(wheel.transform.gameObject); 
            }
            
        }
    }
}